package org.appmon.core.transformer;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.appmon.core.config.BehaviourProperties;
import org.appmon.core.config.ByteCodeModifier;
import org.appmon.core.config.PackageBaseInfo;

import com.google.common.collect.Multimap;

public class MethodCountTransformer implements ClassFileTransformer{

	public byte[] transform(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) throws IllegalClassFormatException {
		
		className=className.replace('/', '.');
		
		System.out.println("MethodCountTransformer-Instumenting Class  : "+className);
		byte[] byteCode = classfileBuffer;

		System.out.println("view Hashcode : "+PackageBaseInfo.getInstance().hashCode());
		Multimap<String, Object> classToInclude = PackageBaseInfo.getInstance().getClassToInclude();
		System.out.println("view Class map : "+classToInclude);
		System.out.println("key clas hash : "+className.hashCode());
//		for(String key:PackageBaseInfo.getInstance().getClassToInclude().keySet()){
//			System.out.println("key val : "+key);
//			System.out.println("key map hash : "+key.hashCode());
//		}
	//	System.out.println("check : "+PackageBaseInfo.getInstance().getClassToInclude().containsKey(className)+" : "+((BehaviourProperties)PackageBaseInfo.getInstance().getClassToInclude().get(className)).isMethodCountable());
		
		System.out.println("check : "+PackageBaseInfo.getInstance().getClassToInclude().containsKey(className));
		if(classToInclude.containsKey(className)){
			
			 Iterator itr = classToInclude.get(className).iterator();
			
			 try {				
			      while(itr.hasNext()) {
			    	  BehaviourProperties element = (BehaviourProperties)itr.next();
			         System.out.print(element + " ");
			      
			         if(element.isMethodCountable() && !element.getClasspath().isEmpty()){
							 System.out.println("Bypass check");	
							 System.out.println("Modifying : "+className+" -- "+loader);
							 ByteCodeModifier bm=new ByteCodeModifier();
							 byteCode=bm.modify(className,element.getClasspath());
							 System.out.println("Instumenting complete ");
			       }
			     }
	            } catch (Exception ex) {
	            	System.out.println("In Catch");
	                ex.printStackTrace();
	            }
			}
	            return byteCode;
	      
	}

}
